package com.example.xmpic.ui.activity.local;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.util.Log;

import com.example.common.base.BaseBindActivity;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.utils.LiveDataBus;
import com.example.common.view.refresh.CustomRefreshView;
import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivityRecordDownloadBinding;
import com.example.xmpic.support.FunPath;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.models.FunFileData;
import com.example.xmpic.ui.adapter.DownloadAdapter;
import com.example.xmpic.ui.data.DownloadState;
import com.example.xmpic.ui.utils.CameraFileUtil;
import com.example.xmpic.ui.data.CameraLocalFile;
import com.example.xmpic.ui.service.DownloadService;
import com.example.xmpic.ui.service.onServiceCallBack;
import com.example.xmpic.ui.utils.LocalFileManager;
import com.example.xmpic.view.BaseTipsDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author skygge
 * @date 2020/6/22.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：回放视频的下载管理
 */
public class RecordDownLoadActivity extends BaseBindActivity<ActivityRecordDownloadBinding> implements DownloadAdapter.onCLickCallBack{

    private FunDevice mFunDevice = null;
    private List<CameraLocalFile> mLocalFile;
    private List<FunFileData> mDownloadFiles;
    private DownloadAdapter mAdapter;

    private String mDownPath;
    private int mCount = 0;
    private boolean mDownloadFinish = true;

    private MyConnection mConnection;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_record_download;
    }

    @Override
    protected void initialize() {
        super.initialize();
        int mCameraId = getIntent().getIntExtra("FUN_DEVICE_ID", 0);
        mFunDevice = FunSupport.getInstance().findDeviceById(mCameraId);
        if (null == mFunDevice) {
            finish();
        }
    }

    @Override
    protected void initView() {
        super.initView();
        mLocalFile = new ArrayList<>();
        mAdapter = new DownloadAdapter(mContext);
        mAdapter.setCallBack(this);
        mDBind.downloadList.setAdapter(mAdapter);
        ((SimpleItemAnimator) Objects.requireNonNull(mDBind.downloadList.getRecyclerView().getItemAnimator())).setSupportsChangeAnimations(false);
    }

    @Override
    protected void initData() {
        super.initData();
        mDownloadFiles = CameraRecordActivity.getChooseFiles();
        mDownPath = FunPath.PATH_VIDEO + File.separator + mFunDevice.getDevSn() + File.separator;
        showFileList(true);
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.ivDownloadBack.setOnClickListener(v -> onFinish());
        mDBind.ivDeleteDownload.setOnClickListener(v -> showClearDownload());
        mDBind.downloadList.setOnLoadListener(new CustomRefreshView.OnLoadListener() {
            @Override
            public void onRefresh() {
                showFileList(false);
                mDBind.downloadList.complete();
            }

            @Override
            public void onLoadMore() {
                mDBind.downloadList.complete();
            }
        });
    }

    /**
     * 显示文件列表
     */
    private void showFileList(boolean startDownload){
        new Thread(()-> {
            List<CameraLocalFile> mLocal = LocalFileManager.getInstance().getLocalVideos(mContext, mFunDevice.getDevSn());
            if (mLocal.size()>0) {
                CameraFileUtil.getInstance().updateLocalFile(mLocal, mFunDevice.getDevSn());
            }
            if (mDownloadFiles.size()>0 && startDownload){
                for (FunFileData fun : mDownloadFiles) {
                    String time = fun.getBeginDateStr() + " " + fun.getBeginTimeStr();
                    String downTime = LocalFileManager.getInstance().getTimeStamp(time);
                    CameraLocalFile download = new CameraLocalFile();
                    String videoName = fun.getBeginDateStr() + "_" + fun.getBeginTimeStr() + "-" + fun.getEndTimeStr() + ".mp4";
                    String path = mDownPath + videoName;
                    download.setDownTime(downTime);
                    download.setSerial(mFunDevice.getDevSn());
                    download.setFilename(videoName);
                    download.setFilepath(path);
                    download.setIsLocalFile(false);
                    CameraFileUtil.getInstance().insertLocalFile(download);
                    mCount++;
                }
            }
            refreshListView();
            if (mCount>0 && startDownload) {
                startService();
            }
        }).start();
    }

    private void startService(){
        mDownloadFinish = false;
        Intent bindIntent = new Intent(getApplication(), DownloadService.class);
        mConnection = new MyConnection();
        bindService(bindIntent, mConnection, BIND_AUTO_CREATE);
    }

    private void refreshListView(){
        mLocalFile = CameraFileUtil.getInstance().findCameraDownload(mFunDevice.getDevSn());
        if (mLocalFile.size()>0){
            mHandler.post(()-> mAdapter.setDownloadFiles(mLocalFile));
        }else {
            mHandler.post(() -> {
                mAdapter.setDownloadFiles(null);
                mDBind.downloadList.setEmptyView(getString(R.string.no_download_file), R.mipmap.scene_empty);
            });
        }
    }

    @Override
    public void onDeleteLocalFile(String downTime) {
        CameraFileUtil.getInstance().deleteByDownTime(downTime);
        refreshListView();
    }

    @Override
    public void onDowning() {
        showToast(mContext.getString(R.string.wait));
    }

    private class MyConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            DownloadService.DownloadBinder mBinder = (DownloadService.DownloadBinder) service;
            mBinder.setRequestCallBack(mCallBack);
            mBinder.setDownloadFile(mFunDevice, mDownloadFiles, mCount);
            mBinder.setLocalFile(mLocalFile);
            mBinder.startToDownload();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    private onServiceCallBack mCallBack = new onServiceCallBack() {
        @Override
        public void onDeviceFileDownCompleted(FunDevice funDevice, String path, int position) {
            Log.i(TAG, "onDeviceFileDownProgressAA: " + position);
            LocalFileManager.getInstance().scanFile(mContext, path);//必须刷新媒体库 否则系统无法获取新下载的文件
            mAdapter.setDownState(DownloadState.DOWNLOAD_SUCCESS, position);
        }

        @Override
        public void onDeviceFileDownProgress(int totalSize, int progress, int position) {
            int current = (int)(progress/100000f);
            mAdapter.setPosition(totalSize, current, position);
            Log.i(TAG, "onDeviceFileDownProgressBB: " + totalSize + "--" + current + "--" + position);
        }

        @Override
        public void onDeviceFileDownStart(boolean isStartSuccess, int position) {
            Log.i(TAG, "onDeviceFileDownProgressCC: " + isStartSuccess + "--" + position);
            if (isStartSuccess){
                mAdapter.setDownState(DownloadState.DOWNLOAD_START, position);
            }
        }

        @Override
        public void onDeviceFileFinish() {
            Log.i(TAG, "onDeviceFileDownProgressDD: finish");
            mDownloadFinish = true;
        }
    };

    private void showClearDownload(){
        if (mLocalFile.size()<=0){
            showToast(getString(R.string.no_download_file));
            return;
        }
        BaseTipsDialog mDialog = new BaseTipsDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                CameraFileUtil.getInstance().deleteAllLocalFile();
                mLocalFile.clear();
                mAdapter.setDownloadFiles(null);
                mDBind.downloadList.setEmptyView(getString(R.string.no_download_file), R.mipmap.scene_empty);
            }

            @Override
            public void onCancel() {

            }
        });
        mDialog.setMsg(getString(R.string.clear_download));
        mDialog.show();
    }

    private void onFinish(){
        if (mDownloadFinish) {
            LiveDataBus.get().with("FUN_DEVICE_ID").setValue(0);
            finish();
        }else {
            BaseTipsDialog mDialog = new BaseTipsDialog(mContext, new OnCallBackToRefresh() {
                @Override
                public void onConfirm() {
                    LiveDataBus.get().with("FUN_DEVICE_ID").setValue(0);
                    finish();
                }

                @Override
                public void onCancel() {

                }
            });
            mDialog.setMsg(getString(R.string.exit_download));
            mDialog.show();
        }
    }

    @Override
    public void onBackPressed() {
        onFinish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mConnection);
    }
}
